package com.htu.courseService.websocket.chat.hanler;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htu.courseService.websocket.chat.enums.ChatOperationEnum;
import com.htu.courseService.websocket.config.NettyConfig;
import com.htu.courseService.websocket.config.SocketMsg;
import com.htu.courseService.websocket.config.SocketUtil;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * Created By JNNarrator on 2024/9/22 01:43
 * email: jiangn09@chinatelecom.cn
 */
@Component("sendMsg")
public class SendMsgChatHandler implements ChatAppHandler{
	@Override
	public void handle(SocketMsg<?> socketMsg, ChannelHandlerContext ctx) {
		String msgStr = ((JSONObject)socketMsg.getData()).getString("msg");
		JSONArray userIds = ((JSONObject)socketMsg.getData()).getJSONArray("userIds");
		SocketMsg<String> msg = SocketMsg.build(ChatOperationEnum.SEND_MSG, msgStr);
		msg.setAuthToken(socketMsg.getAuthToken());
		if (CollectionUtils.isEmpty(userIds) || "".equals(userIds.get(0))){
			//群发
			NettyConfig.getChannelMap().forEach(
					(userId, channel) -> {
						if (userId.equals(socketMsg.getAuthToken())){
							return;
						}
						SocketUtil.channel(channel).sendMsgChannel(msg);
					}
			);
		}else {
			userIds.stream().iterator().forEachRemaining(o -> SocketUtil.channel(NettyConfig.getChannel((String) o)).sendMsgChannel(msg));
		}
	}
}
